package com.henushang.picture_pedia.picture_utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.log4j.Logger;

import com.henushang.picture_pedia.domain.ResponseVo;

public class CarUtil {
    private static Logger logger = Logger.getLogger(CarUtil.class);
    private static String CAR_URL = "https://aip.baidubce.com/rest/2.0/image-classify/v1/car";
    
    public static void main(String[] args) {
        System.out.println(getCarInfo("C:\\Users\\henushang\\Desktop\\bmw\\timg.jpg"));
    }
    
    public static ResponseVo getCarInfo(String picPath, int topNum) {
String getCarInfoUrl = CAR_URL + "?access_token=" + BaiduCloudUtil.getAuth();
        
        try {
            URL realUrl = new URL(getCarInfoUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setDoOutput(true);
            connection.connect();
            
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes(getRequestBody(picPath, topNum));;
            out.flush();
            out.close();
            
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            
            return ResponseVo.successInstance(result);
        } catch (Exception e) {
            logger.error("get car info error, path:" + picPath);
        }
        return ResponseVo.failInstance("");
    }
    
    public static ResponseVo getCarInfo(String picPath) {
        return getCarInfo(picPath, 5);
    }
    
    private static String getRequestBody(String path, int topNum) {
        String body = "";
        
        String imageEncode = ImageUtil.readImageFromLocal(path);
        try {
            body = "image=" + URLEncoder.encode(imageEncode, "UTF-8") + "&top_num=" + topNum;
        } catch (Exception e) {
            logger.error("get request body error, path:" + path + ", topNum: " + topNum, e);
        }
        return body;
    }
}
